(function() {
	// Cookie Functions
	const setCookie = (name, value, days) => {
		const date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		const expires = "expires=" + date.toUTCString();
		document.cookie = `${name}=${value}; ${expires}; path=/`;
	};

	const getCookie = (name) => {
		const nameEQ = `${name}=`;
		const ca = document.cookie.split(';');
		for (let i = 0; i < ca.length; i++) {
			let c = ca[i].trim();
			if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
		}
		return null;
	};

	// Theme Functions
	const setInitialTheme = () => {
		const theme = getCookie('theme');
		if (theme) {
			document.documentElement.classList.toggle('dark-theme', theme === 'dark');
		} else {
			const hour = new Date().getHours();
			const isNightTime = hour >= 17 || hour < 7;
			document.documentElement.classList.toggle('dark-theme', isNightTime);
		}
	};

	document.getElementById('button-mode').addEventListener('click', () => {
		const htmlElement = document.documentElement;
		const isDarkTheme = htmlElement.classList.toggle('dark-theme');
		setCookie('theme', isDarkTheme ? 'dark' : 'light', 365);
	});

	setInitialTheme();

	// Typed.js Initialization
	const initializeTyped = () => {
		new Typed("#text", {
			strings: [
				"欢迎小可爱来到我的主页",
				"在这里你能更好的了解我",
				"喜欢欣赏世界的美好，喜欢美妙的计算机世界"
			],
			typeSpeed: 100,
			smartBackspace: true,
			backSpeed: 50,
			backDelay: 500,
			cursorChar: '',
			loop: false,
			startDelay: 1000,
			fadeOut: true,
		});
	};

	document.addEventListener('DOMContentLoaded', initializeTyped);

	// Lazy Loading Images
	document.addEventListener("DOMContentLoaded", () => {
		const lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));

		if ("IntersectionObserver" in window) {
			const lazyImageObserver = new IntersectionObserver((entries, observer) => {
				entries.forEach(entry => {
					if (entry.isIntersecting) {
						const lazyImage = entry.target;
						lazyImage.src = lazyImage.dataset.src;
						lazyImage.classList.remove("lazy");
						lazyImageObserver.unobserve(lazyImage);
					}
				});
			}, {
				rootMargin: '0px 0px 50px 0px',
				threshold: 0.01
			});

			lazyImages.forEach(lazyImage => lazyImageObserver.observe(lazyImage));
		} else {
			const lazyLoad = () => {
				if (!active) {
					active = true;
					setTimeout(() => {
						lazyImages.forEach(lazyImage => {
							if ((lazyImage.getBoundingClientRect().top <= window
									.innerHeight &&
									lazyImage.getBoundingClientRect().bottom >= 0) &&
								getComputedStyle(lazyImage).display !== "none") {
								lazyImage.src = lazyImage.dataset.src;
								lazyImage.classList.remove("lazy");
								lazyImages = lazyImages.filter(image => image !==
									lazyImage);

								if (lazyImages.length === 0) {
									document.removeEventListener("scroll", lazyLoad);
									window.removeEventListener("resize", lazyLoad);
									window.removeEventListener("orientationchange",
										lazyLoad);
								}
							}
						});
						active = false;
					}, 200);
				}
			};

			let active = false;
			document.addEventListener("scroll", lazyLoad);
			window.addEventListener("resize", lazyLoad);
			window.addEventListener("orientationchange", lazyLoad);
		}
	});

	// Seniverse Weather Widget Initialization
	document.addEventListener("DOMContentLoaded", function() {
		(function(a, h, g, f, e, d, c, b) {
			b = function() {
				d = h.createElement(g);
				c = h.getElementsByTagName(g)[0];
				d.src = e;
				d.charset = "utf-8";
				d.async = 1;
				c.parentNode.insertBefore(d, c);
			};
			a["SeniverseWeatherWidgetObject"] = f;
			a[f] || (a[f] = function() {
				(a[f].q = a[f].q || []).push(arguments);
			});
			a[f].l = +new Date();
			if (a.attachEvent) {
				a.attachEvent("onload", b);
			} else {
				a.addEventListener("load", b, false);
			}
		})(window, document, "script", "SeniverseWeatherWidget",
			"//cdn.sencdn.com/widget2/static/js/bundle.js?t=" +
			parseInt((new Date().getTime() / 100000000).toString(), 10));

		window.SeniverseWeatherWidget('show', {
			flavor: "slim",
			location: "WTME8U3BYPEU",
			geolocation: true,
			language: "zh-Hans",
			unit: "c",
			theme: "auto",
			token: "33e5ce3d-c612-4e5b-a88b-d98a90dab11d",
			hover: "disabled",
			container: "tp-weather-widget"
		});
	});

	// Date and Time Update Functions
	const updateDateTime = () => {
		const currentDate = new Date();
		const year = currentDate.getFullYear();
		const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
		const day = currentDate.getDate().toString().padStart(2, '0');
		const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
		const dayOfWeek = daysOfWeek[currentDate.getDay()];
		const hours = currentDate.getHours().toString().padStart(2, '0');
		const minutes = currentDate.getMinutes().toString().padStart(2, '0');
		const seconds = currentDate.getSeconds().toString().padStart(2, '0');
		const formattedDate = `${year} 年 ${month} 月 ${day} 日 星期${dayOfWeek}`;
		const formattedTime = `${hours}:${minutes}:${seconds}`;

		document.getElementById('currentdate').textContent = formattedDate;
		document.getElementById('currenttime').textContent = formattedTime;
	};

	window.onload = updateDateTime;
	setInterval(updateDateTime, 1000);

	const updateTime = () => {
		const now = new Date();
		const todayEndTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
		const todayRemainingMillis = todayEndTime - now;
		const todayHoursRemaining = Math.floor(todayRemainingMillis / (1000 * 60 * 60));

		document.getElementById('todayHoursPassed').textContent = now.getHours();
		document.getElementById('todayHoursRemaining').textContent = todayHoursRemaining;
		document.getElementById('todayPercentage').textContent = Math.round((now.getHours() / 24) * 100) + '%';
	};

	updateTime();
	setInterval(updateTime, 1000);

	// 实时检测非法访问并显示提示信息
	function detectIllegalAccess() {
		let ua = navigator.userAgent.toLowerCase();
		let isMobile = /mobile|android|iphone|ipad|phone/i.test(ua);
		let noticeDiv = document.getElementById('notice');
		let isIllegal = false;
		let closeTimeout = null;

		function checkWindowSize() {
			let shouldBeIllegal = false;

			if (isMobile && window.innerWidth <= 300) {
				shouldBeIllegal = true;
			} else if (!isMobile && window.innerWidth < 1000) {
				shouldBeIllegal = true;
			}

			if (shouldBeIllegal && !isIllegal) {
				showNotice();
				isIllegal = true;
			} else if (!shouldBeIllegal && isIllegal) {
				hideNotice();
				isIllegal = false;
				cancelCloseTimeout();
			}
		}

		function showNotice() {
			noticeDiv.textContent = '您为非授权访问，正在自动重定向！';
			noticeDiv.style.display = 'block';
			setCloseTimeout();
		}

		function hideNotice() {
			noticeDiv.style.display = 'none';
			cancelCloseTimeout();
		}

		function setCloseTimeout() {
			closeTimeout = setTimeout(function() {
				window.location.href = "https://www.bbixb.top/";
			}, 3000);
		}

		function cancelCloseTimeout() {
			if (closeTimeout) {
				clearTimeout(closeTimeout);
				closeTimeout = null;
			}
		}

		// 初次加载和窗口大小变化时检测
		checkWindowSize();
		window.addEventListener('resize', checkWindowSize);
	}

	document.addEventListener('DOMContentLoaded', function() {
		detectIllegalAccess();

		// 禁用右键菜单
		document.addEventListener('contextmenu', function(e) {
			e.preventDefault();
		}, false);

		// 禁用文本选择
		document.addEventListener('selectstart', function(e) {
			e.preventDefault();
		}, false);

		// 禁用复制功能
		document.addEventListener('copy', function(e) {
			e.preventDefault();
		}, false);

		// 禁用所有快捷键
		document.addEventListener('keydown', function(e) {
			// 禁用F12、Ctrl+Shift+I、Ctrl+Shift+J、Ctrl+U、Ctrl+S、Ctrl+P
			if (e.keyCode === 123 ||
				(e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74)) ||
				(e.ctrlKey && (e.keyCode === 85 || e.keyCode === 83 || e.keyCode === 80))) {
				e.preventDefault();
				return false;
			}
		}, false);

		// 禁用图片拖动
		document.addEventListener('dragstart', function(e) {
			if (e.target.tagName.toLowerCase() === 'img') {
				e.preventDefault();
			}
		}, false);

		// 禁用鼠标滚轮缩放
		document.addEventListener('wheel', function(e) {
			if (e.ctrlKey) {
				e.preventDefault();
			}
		}, {
			passive: false
		});

		// 禁用键盘缩放快捷键 (Ctrl + +/-)
		document.addEventListener('keydown', function(e) {
			if ((e.ctrlKey && (e.key === '+' || e.key === '-')) || e.key === 'Meta') {
				e.preventDefault();
			}
		});

		// 禁用双指缩放手势
		document.addEventListener('gesturestart', function(e) {
			e.preventDefault();
		});
		document.addEventListener('gesturechange', function(e) {
			e.preventDefault();
		});
		document.addEventListener('gestureend', function(e) {
			e.preventDefault();
		});
	});
})();